<?php
/**
 * Created by PhpStorm.
 * User: huawei
 * Date: 2021/4/7
 * Time: 11:07
 */

namespace app\admin\controller;

use app\BaseController;
use app\model\AdminUser;
use think\App;
use think\facade\Cache;
use think\facade\Session;

class Login extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public $loginKey = "loginkey";

    private function loginget(){
        if(Cache::has($this->loginKey)){
            $num = Cache::get($this->loginKey);
            if((int)$num>=6){
                return false;
            }
        };
        return true;
    }

    private function loginset(){
        if(Cache::has($this->loginKey)){
            $num = Cache::get($this->loginKey);
            $val = (int)$num+1;
            Cache::set($this->loginKey,$val,60);
        }else{
            Cache::set($this->loginKey,1,60);
        };
    }

    /**
     * @title 验证码
     * @return \think\Response
     */
    public function captcha_src(){
        return captcha();
    }

    public function index(){
        if($this->request->isPost()){
            if(!$this->loginget()){
                return $this->error(lang("loginRestricted"));
            }
            $data = $this->request->post();

            $check = $this->validate($data,[
                'captcha|'.lang("captcha")=>'require|captcha',
                'username|'.lang("username")=>'require',
                'password|'.lang("pass")=>'require',
            ]);
            if($check){

                return $this->error($check);
            }
            $user = AdminUser::where("username",$data["username"])->find();
            if(!$user){
                $this->loginset();
                return $this->error(lang("Account.does.not.exist"));
            }
            if($user->display!=1){
                $this->loginset();
                return $this->error(lang(Account.is.blocked));
            }
            $salf = $user->salt;
            $pass = md5pass($data["password"],$salf);

            if($pass!=$user->pass){
                $this->loginset();
                return $this->error(lang("wrong.password"));
            }
            $user->login_ip = $this->request->ip();
            $user->login_time = date("Y-m-d H:i:s");
            Session::set($this->adminkey,$user->toArray());
            return $this->success(lang("login").lang("success"));
        }else{
            return $this->view("");
        }

    }

}